/**
 * @Author: Greg Mercer
 * Copyright © 2020 Jungle Scout
 *
 * Filter drawer operations
 */

$(function() {
  //If the file has injected many times
  if ($('.jsContainer').length >= 1) {
    return
  }

  //Images resources
  var imagesPath = chrome.extension.getURL('images')
  var completeActive = imagesPath + '/icons/complete-active.png'
  var loadingActive = imagesPath + '/icons/loading-active.png'

  //----------------------------------------------------//
  $('body').on('change input', '.filter-inputs-container input', function(e) {
    $('#jsFilterResultsBtn').removeClass('js-gray-btn')
  })

  //----------------------------------------------------//
  //On click on clear button
  $('body').on('click', '.filter-drawer #resetFilterBtn', function(e) {
    e.preventDefault()
    $('#js-table tbody tr:not(.child-product)').show()
    $('.filter-inputs-container input').val('')
    $(".filter-inputs-container input[type='checkbox']").prop('checked', true)

    //Recalculate avg. boxes
    renderHeaderBoxes(true)

    //Deactive the filter button
    $('.filter-inputs-container #jsFilterResultsBtn').addClass('js-gray-btn')
    $('section.jsContainer #js-table').attr('js-filter-mode', 'false')
  })

  //----------------------------------------------------//
  //Start filter the results
  $('body').on('click', '.filter-inputs-container #jsFilterResultsBtn', function(e) {
    e.preventDefault()
    filterBtnInProcess()
    //Show all rows
    $('#js-table tbody tr').show()
    //Price Columns
    if (showPriceColumn) {
      var priceHeader = $('#js-table th.js-price').index()
      var price1 = $(".filter-inputs-container input[name='minPrice']").val()
      var price2 = $(".filter-inputs-container input[name='maxPrice']").val()

      if (price1 || price2) {
        var rows = $('#js-table tbody')
          .find('tr')
          .filter(':visible')
          .hide()
        price1 = price1 ? parseFloat(price1) : 0
        price2 = price2 ? parseFloat(price2) : 1000000

        $.each(rows, function(index, row) {
          var thePrice = $(row)
            .find('td')
            .eq(priceHeader)
            .text()
          thePrice = thePrice.replace(/[\$\€\£\₹\,]|(--i)/g, '')
          thePrice = parseFloat(thePrice)
          if (!isNaN(thePrice) && thePrice >= price1 && thePrice <= price2) {
            $(row).show()
          }
        })
      }
    }

    //Reviews
    if (showReviewsColumn) {
      var reviewsHeader = $('#js-table th.js-reviews').index()
      var reviews1 = $(".filter-inputs-container input[name='minReviews']").val()
      var reviews2 = $(".filter-inputs-container input[name='maxReviews']").val()

      if (reviews1 || reviews2) {
        var rows = $('#js-table tbody')
          .find('tr')
          .filter(':visible')
          .hide()
        reviews1 = reviews1 ? parseInt(reviews1) : 0
        reviews2 = reviews2 ? parseInt(reviews2) : 1000000
        $.each(rows, function(index, row) {
          var theReviews = $(row)
            .find('td')
            .eq(reviewsHeader)
            .text()
          theReviews = theReviews.replace(/(--i)/, '')
          theReviews = parseInt(theReviews)
          if (!isNaN(theReviews) && theReviews >= reviews1 && theReviews <= reviews2) {
            $(row).show()
          }
        })
      }
    }

    //Rank
    if (showRankColumn) {
      var rankHeader = $('#js-table th.js-rank').index()
      var rank1 = $(".filter-inputs-container input[name='minRank']").val()
      var rank2 = $(".filter-inputs-container input[name='maxRank']").val()

      if (rank1 || rank2) {
        var rows = $('#js-table tbody tr')
          .filter(':visible')
          .hide()
        rank1 = rank1 ? parseInt(rank1) : 0
        rank2 = rank2 ? parseInt(rank2) : 1000000

        $.each(rows, function(index, row) {
          var theRank = $(row)
            .find('td')
            .eq(rankHeader)
            .text()
          theRank = theRank.replace(/(--i)|[\,\#]/g, '')
          theRank = parseInt(theRank)
          if (!isNaN(theRank) && theRank >= rank1 && theRank <= rank2) {
            $(row).show()
          }
        })
      }
    }

    //Estimated Sales
    if (showEstSalesColumn) {
      var estSalesHeader = $('#js-table th.js-est-sales-mo').index()
      var estSales1 = $(".filter-inputs-container input[name='minEstSales']").val()
      var estSales2 = $(".filter-inputs-container input[name='maxEstSales']").val()
      if (estSales1 || estSales2) {
        var rows = $('#js-table tbody tr')
          .filter(':visible')
          .hide()
        estSales1 = estSales1 ? parseFloat(estSales1) : 0
        estSales2 = estSales2 ? parseFloat(estSales2) : 1000000
        $.each(rows, function(index, row) {
          var theEstSales = $(row)
            .find('td')
            .eq(estSalesHeader)
            .text()
          theEstSales = theEstSales.replace(/[\,]|(--i)/g, '')
          theEstSales = theEstSales.replace(/(\<\s?[0-9]+)/g, '0.00')
          theEstSales = parseFloat(theEstSales)
          if (!isNaN(theEstSales) && theEstSales >= estSales1 && theEstSales <= estSales2) {
            $(row).show()
          }
        })
      }
    }

    //Estimated Revenue
    if (showEstRevenueColumn) {
      var estRevenueHeader = $('#js-table th.js-est-revenue').index()
      var estRevenue1 = $(".filter-inputs-container input[name='minEstRevenue']").val()
      var estRevenue2 = $(".filter-inputs-container input[name='maxEstRevenue']").val()
      if (estRevenue1 || estRevenue2) {
        var rows = $('#js-table tbody tr')
          .filter(':visible')
          .hide()
        estRevenue1 = estRevenue1 ? parseFloat(estRevenue1) : 0
        estRevenue2 = estRevenue2 ? parseFloat(estRevenue2) : 1000000

        $.each(rows, function(index, row) {
          var theEstRevenue = $(row)
            .find('td')
            .eq(estRevenueHeader)
            .text()
          theEstRevenue = theEstRevenue.replace(/[\$\€\£\₹\,]|(\<\s)|(--i)/g, '')
          theEstRevenue = parseFloat(theEstRevenue)
          if (
            !isNaN(theEstRevenue) &&
            theEstRevenue >= estRevenue1 &&
            theEstRevenue <= estRevenue2
          ) {
            $(row).show()
          }
        })
      }
    }

    //Rating
    if (showRatingColumn) {
      var ratingHeader = $('#js-table th.js-rating').index()
      var rate1 = $(".filter-inputs-container input[name='minRate']").val()
      var rate2 = $(".filter-inputs-container input[name='maxRate']").val()

      if (rate1 || rate2) {
        var rows = $('#js-table tbody tr')
          .filter(':visible')
          .hide()
        rate1 = rate1 ? parseFloat(rate1) : 0
        rate2 = rate2 ? parseFloat(rate2) : 1000000

        $.each(rows, function(index, row) {
          var theRate = $(row)
            .find('td')
            .eq(ratingHeader)
            .text()
          theRate = theRate.replace(/(--i)/, '')
          theRate = parseFloat(theRate)
          if (!isNaN(theRate) && theRate >= rate1 && theRate <= rate2) {
            $(row).show()
          }
        })
      }
    }

    //BB Seller
    if (showBbSellerColumn) {
      var bbSellerHeader = $('#js-table th.js-bb-seller').index()
      var amz = $(".filter-inputs-container input[name='amz']:checked").length > 0 ? true : false
      var fba = $(".filter-inputs-container input[name='fba']:checked").length > 0 ? true : false
      var merch =
        $(".filter-inputs-container input[name='merch']:checked").length > 0 ? true : false

      if (amz && fba && merch) {
        //Do nothing
      } else if (amz || fba || merch) {
        var rows = $('#js-table tbody tr')
          .filter(':visible')
          .hide()
        $.each(rows, function(index, row) {
          var theBBSeller = $(row)
            .find('td')
            .eq(bbSellerHeader)
            .text()
          theBBSeller = theBBSeller.replace(/(--i)/, '')
          if (
            (amz && theBBSeller == 'AMZ') ||
            (fba && theBBSeller == 'FBA') ||
            (merch && theBBSeller == 'FBM')
          ) {
            $(row).show()
          }
        })
      }
    }

    //Weight
    if (showItemWeightColumn) {
      var weightHeader = $('#js-table th.js-item-weight').index()
      var weight1 = $(".filter-inputs-container input[name='minWeight']").val()
      var weight2 = $(".filter-inputs-container input[name='maxWeight']").val()

      if (weight1 || weight2) {
        var rows = $('#js-table tbody tr')
          .filter(':visible')
          .hide()
        weight1 = weight1 ? parseFloat(weight1) : 0
        weight2 = weight2 ? parseFloat(weight2) : 1000000
        $.each(rows, function(index, row) {
          var theWeight = $(row)
            .find('td')
            .eq(weightHeader)
            .text()
          theWeight = theWeight.replace(/(--i)/, '')
          theWeight = parseFloat(theWeight)
          if (!isNaN(theWeight) && theWeight >= weight1 && theWeight <= weight2) {
            $(row).show()
          }
        })
      }
    }

    //Sellers
    if (showNewSellerColumn) {
      var sellersHeader = $('#js-table th.js-new-sellers').index()
      var seller1 = $(".filter-inputs-container input[name='minSeller']").val()
      var seller2 = $(".filter-inputs-container input[name='maxSeller']").val()

      if (seller1 || seller2) {
        var rows = $('#js-table tbody tr')
          .filter(':visible')
          .hide()
        seller1 = seller1 ? parseInt(seller1) : 0
        seller2 = seller2 ? parseInt(seller2) : 1000000

        $.each(rows, function(index, row) {
          var theSellers = $(row)
            .find('td')
            .eq(sellersHeader)
            .text()
          theSellers = theSellers.replace(/(--i)/, '')
          theSellers = parseInt(theSellers)
          if (!isNaN(theSellers) && theSellers >= seller1 && theSellers <= seller2) {
            $(row).show()
          }
        })
      }
    }

    //Tier
    if (showTierColumn) {
      var tierHeader = $('#js-table th.js-tier').index()
      var standard =
        $(".filter-inputs-container input[name='tierStandard']:checked").length > 0 ? true : false
      var oversize =
        $(".filter-inputs-container input[name='tierOversize']:checked").length > 0 ? true : false
      if (standard && oversize) {
        //Do nothing
      } else if (standard || oversize) {
        var rows = $('#js-table tbody tr')
          .filter(':visible')
          .hide()

        $.each(rows, function(index, row) {
          var theTier = $(row)
            .find('td')
            .eq(tierHeader)
            .text()
          theTier = theTier.replace(/(--i)/, '')

          if (
            (standard && (theTier == 'Stand' || theTier == 'S. Stand' || theTier == 'L. Stand')) ||
            (oversize &&
              (theTier == 'S. Over' ||
                theTier == 'O. Over' ||
                theTier == 'M. Over' ||
                theTier == 'L. Over' ||
                theTier == 'R. Over' ||
                theTier == 'Special'))
          ) {
            $(row).show()
          }
        })
      }
    }

    //Net
    if (showNetColumn) {
      var netHeader = $('#js-table th.js-net').index()
      var net1 = $(".filter-inputs-container input[name='minNet']").val()
      var net2 = $(".filter-inputs-container input[name='maxNet']").val()
      if (net1 || net2) {
        var rows = $('#js-table tbody tr:visible').hide()
        net1 = net1 ? parseFloat(net1) : 0
        net2 = net2 ? parseFloat(net2) : 1000000
        $.each(rows, function(index, row) {
          var theNet = $(row)
            .find('td')
            .eq(netHeader)
            .text()
          theNet = theNet.replace(/[\$\€\£\₹\,]|(--i)/g, '')
          theNet = theNet.replace(/(\<\s?[0-9]+)/g, '0')
          theNet = parseFloat(theNet)
          if (!isNaN(theNet) && theNet >= net1 && theNet <= net2) {
            $(row).show()
          }
        })
      }
    }

    //Lqs
    if (showLQSColumn) {
      var lqsHeader = $('#js-table th.js-lqs').index()
      var lqs1 = $(".filter-inputs-container input[name='minLQS']").val()
      var lqs2 = $(".filter-inputs-container input[name='maxLQS']").val()
      if (lqs1 || net2) {
        var rows = $('#js-table tbody tr')
          .filter(':visible')
          .hide()
        lqs1 = lqs1 ? parseFloat(lqs1) : 0
        lqs2 = lqs2 ? parseFloat(lqs2) : 1000000
        $.each(rows, function(index, row) {
          var theLQS = $(row)
            .find('td')
            .eq(lqsHeader)
            .text()
          theLQS = parseInt(theLQS)
          if (!isNaN(theLQS) && theLQS >= lqs1 && theLQS <= lqs2) {
            $(row).show()
          }
        })
      }
    }

    //Check if all rows are hidden
    if ($('#js-table tbody tr:visible').length == 0) {
      showNoProductsScreen('filter')
    } else {
      $('section.jsContainer .main-screen').css('display', 'none')
      $('section.jsContainer #js-table').css('margin-bottom', '15px')
    }

    //Recalculate avg. boxes
    // renderHeaderBoxes(true)
    // $('body').trigger('onTableRowChanged', true)
    setTimeout(function() {
      filterSuccessState()
    }, 1000)

    //Add a mark we are in filter mode
    $('section.jsContainer #js-table').attr('js-filter-mode', 'true')
  }) //End filter button

  //---------------------------------------------------------------------------------//
  function filterSuccessState(callback) {
    let $filterSubmitBtn = $('.filter-inputs-container #jsFilterResultsBtn')
    $('.filter-inputs-container #jsFilterResultsBtn span').fadeOut(500, function() {
      $(this)
        .html("<img src='" + completeActive + "' />")
        .fadeIn(500, function() {
          $filterSubmitBtn.fadeOut(500, function() {
            $filterSubmitBtn.html($filterSubmitBtn.attr('data-content')).fadeIn(500)
            $filterSubmitBtn.addClass('js-gray-btn')
          })
        })
    })
  }

  //---------------------------------------------------------------------------------//
  function filterBtnInProcess() {
    let $filterSubmitBtn = $('.filter-inputs-container #jsFilterResultsBtn')
    $filterSubmitBtn.attr('data-content', $filterSubmitBtn.html())
    $filterSubmitBtn
      .find('span')
      .html(
        "<img src='" + loadingActive + "' width='15px' height='15px' class='js-processing-btn'/>"
      )
  }

  //----------------------------------------------------//
  //If the user input a text
  $('body').on('keyup', '.filter-inputs-container input', function(e) {
    var key = e.which
    if (key == 13) {
      $('.filter-inputs-container #jsFilterResultsBtn').click()
      return false
    }

    if ($(this).val().length == 0 || isNaN($(this).val())) {
      let theInputVal = $(this).val()
      $(this).val(theInputVal.substring(0, theInputVal.length - 1))
      return false
    }
  })
})
